# -*- coding: utf-8 -*
'''
    Created by XiaoInk at 2021/10/08 22:33:53
    Gitee: https://gitee.com/XiaoInk
'''

import redis
import pymysql

from typing import Dict, List

from dbutils.pooled_db import PooledDB


class MYSQL(object):

    def __init__(self, **kwargs):
        self._pool = PooledDB(
            pymysql,
            mincached=5,
            maxcached=10,
            **kwargs,
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor
        )

    def execute(self, sql: str, *args: list or tuple, many: bool = False) -> None or Dict or List[Dict]:
        '''
        :param sql 执行语句
        :param many 返回数据条目, True: None or List[Dict], False: None or Dict
        '''
        conn = self._pool.connection()
        try:
            with conn.cursor() as cur:
                cur.execute(sql, *args)
                if many:
                    return cur.fetchall()
                else:
                    return cur.fetchone()
        finally:
            conn.commit()
            conn.close()

    def executemany(self):
        pass


class REDIS(object):

    def __init__(self, **kwargs):
        self._pool = redis.ConnectionPool(**kwargs)
        self._conn = redis.Redis(connection_pool=self._pool)


def get_mysql(**kwargs):
    return MYSQL(**kwargs)


def get_redis(**kwargs):
    return REDIS(**kwargs)._conn


if __name__ == '__main__':
    pass
